import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { ActivatedRoute, Params } from '@angular/router';
import { UtilsService } from '../../service/utils.service';
import { BaseService } from '../../service/base.service';
import { UserService } from '../../service/user.service';
import { CrtptoService } from '../../service/crtptojs';
import { YearawardService } from './yearaward.service';
import { ActivityingComponent } from './activitying/activitying.component';
import SwiperCore, { SwiperOptions } from 'swiper';

import { fail } from 'assert';
import { Observable, Observer, Subject } from 'rxjs';
declare var hideAndroidWebView: any;
declare var hideIosWebView: any;
declare var androidIntentPayment: any;
@Component({
  selector: 'app-yearaward',
  templateUrl: './yearaward.component.html',
  styleUrls: [
    './yearaward.component.scss',
    './commonList.scss',
    './renq-task-dialog.component.scss',
  ],
})
export class YearawardComponent implements OnInit {
  @ViewChild('wrap', { static: false }) wrap: ElementRef;
  config: SwiperOptions = {
    slidesPerView: 5,
    loop: true,
    slideToClickedSlide: true,
    centeredSlides: true,
    pagination: { clickable: true },
    scrollbar: { draggable: true },
  };
  /* ___ 人气榜-每日任务-弹窗 ___ */
  public showTaskDialog: boolean = false;
  public task: any = {};
  /* ___ _ ___ */
  subscribeScoll: any;
  public flag = true;
  public yuTaskDayShow = false; // 访问住活动页是否弹出领取成功
  public roomPage: string = ''; // 进入房间看到的活动
  public lastRoomPage: string = '';
  public token: string; // token
  public sex: number | string = 2; // 状态1男2女 默认女
  public isandroid: boolean = false; // 是否是android
  public activityStart: string = 'notstsart'; // start notstart end
  public roomid: string; // 当前的房间号,客户端传递
  public startDate: any;
  public endDate: any;
  public ispc: boolean = false;
  public userid: string;
  public onRefrash: boolean = false; // 是否刷新
  public timeConfig: any[] = [];
  public mp4Hide: boolean = false;
  public deployUrl: string = '';
  public isRewardShow = false; /* 奖励弹窗 */
  public top = 0;
  public isReword = false; // 签到福利弹窗
  public complete = 0;
  public total = 0;
  public isSign = false;
  public numh = 0;
  public defaultTabArray: any = [];
  public currentTabArray: any = [];
  public nextTabArray: any = [];
  public rewordList: any = [
    { day: 1, mar: '0.3rem 0.17rem 0 1rem', tips: '「5与伦比」勋章*1天' },
    { day: 2, mar: '0.3rem 1rem 0 0.17rem', tips: '「5与伦比」勋章*2天' },
    { day: 3, mar: '0.3rem 0.07rem 0', tips: '「5与伦比」勋章*3天' },
    { day: 4, mar: '0.3rem 0.07rem 0', tips: '「炫彩小摩托」*2天' },
    { day: 5, mar: '0.3rem 0.07rem 0', tips: '「炫彩小摩托」*5天' },
  ];
  private baseTask = {
    desc: `恭喜您今日首次访问活动页面 获得人气票*` /* 5/10 */,
    allComplete: false,
    getRewardNumber: 5,
    sort: 5,
    taskTotalRounds: 10,
    currentCompleteRounds: 1,
    code: 4,
    remark: '每日登录活动页面',
  }; /* 每日弹窗内容 */
  public titleArray: any = [];
  // 倒计时
  public hoursRightNum: number = 0;
  public hoursLeftNum: number = 0;
  public fenRightNum: number = 0;
  public fenLeftNum: number = 0;
  public miaoRightNum: number = 0;
  public miaoLeftNum: number = 0;
  public androidVersion: number;
  public contentOpacity = 0; // 透明度
  public isDayLook: boolean;
  constructor(
    private utilsservice: UtilsService,
    private route: ActivatedRoute,
    private baseservice: BaseService,
    private yearawardService: YearawardService,
    private userService: UserService,
    private crtptoService: CrtptoService
  ) {}
  ngOnInit() {
    this.deployUrl = this.userService.getDeployUrl();
    this.ispc = this.userService.getIsPc();
    this.isandroid = this.utilsservice.getBrowserVersion();
    if (this.ispc) {
      // pc 传参和app不同,分别处理
      this.route.queryParams.subscribe((params: Params) => {
        this.sex = params.sex;
        if (params.postData === undefined || params.postData === '') {
          this.token = this.baseservice.getUserToken();
          this.roomid = this.baseservice.getRoomid() || '0';
        } else {
          const postData = JSON.parse(
            this.crtptoService.decryptedDES(params.postData)
          );
          this.token = postData.token;
          this.roomid = postData.roomid || '0';
          this.userid = postData.uid;
          this.baseservice.setRoomid(this.roomid);
          this.baseservice.setUserid(this.userid);
          this.baseservice.setUserToken(this.token);
          this.baseservice.setImei(postData.imei);
        }
      });
    } else {
      // app
      this.route.queryParams.subscribe((params: Params) => {
        if (params.token === undefined || params.token === '') {
          this.token = this.baseservice.getUserToken();
          this.roomid = this.baseservice.getRoomid() || '0';
        } else {
          this.token = params.token;
          this.roomid = params.roomid || '0';
          this.userid = params.uid;
          this.sex = params.sex;
          this.baseservice.setUserid(this.userid);
          this.baseservice.setRoomid(this.roomid);
          this.baseservice.setUserToken(this.token);
          this.baseservice.setImei(new Date().getTime());
          this.baseservice.setVersionCode(params.versionCode);
        }
      });
    }
    const userAgent = navigator.userAgent;
    const index = userAgent.indexOf('Android');
    if (index >= 0) {
      this.androidVersion = parseFloat(userAgent.slice(index + 8));
    }
    // 正式代码
    this.getActivityTime().then((res: any) => {
      this.getVisitActivity();
      this.currentTabArray = this.defaultTabArray;
      if (this.sex === 1 || this.sex === '1') {
        this.roomPage = 'nanshen';
      } else if (this.sex === 2 || this.sex === '2') {
        this.roomPage = 'nvshen';
      } else if (this.sex === 0 || this.sex === '0') {
        this.currentTabArray[0].tabActive = true;
        this.roomPage = 'xinxiu';
      } else {
        const dateTime = new Date().getTime();
        if (
          // 如果是女神榜
          dateTime >= this.currentTabArray[3].startTime * 1000 &&
          dateTime <= this.currentTabArray[3].endTime * 1000
        ) {
          this.roomPage = 'nvshen';
        } else if (
          // 如果是男神榜
          dateTime >= this.currentTabArray[2].startTime * 1000 &&
          dateTime <= this.currentTabArray[2].endTime * 1000
        ) {
          this.roomPage = 'nanshen';
        } else if (
          // 如果是新秀榜
          dateTime >= this.currentTabArray[0].startTime * 1000 &&
          dateTime <= this.currentTabArray[0].endTime * 1000
        ) {
          this.roomPage = 'xinxiu';
        } else if (
          // 如果是人气榜
          dateTime >= this.currentTabArray[1].startTime * 1000 &&
          dateTime <= this.currentTabArray[1].endTime * 1000
        ) {
          this.roomPage = 'renqi';
        } else if (
          // 如果是神豪榜
          dateTime >= this.currentTabArray[4].startTime * 1000 &&
          dateTime <= this.currentTabArray[4].endTime * 1000
        ) {
          this.roomPage = 'shenhao';
        }
      }
    });
    // 正式代码end
    if (this.androidVersion < 8) {
      this.mp4Hide = true;
      this.contentOpacity = 1;
      return;
    }
    const playtime = window.localStorage.getItem('readlivecourse');
    const date = new Date().getTime().toString();
    let isDayLook = false;
    if (!playtime) {
      isDayLook = false;
      window.localStorage.setItem('readlivecourse', date);
    } else {
      if (parseFloat(date) - parseFloat(playtime) > 18 * 60 * 60 * 1000) {
        isDayLook = false;
        window.localStorage.setItem('readlivecourse', date);
      } else {
        isDayLook = true;
      }
    }
    this.isDayLook = isDayLook;
    if (isDayLook) {
      this.mp4Hide = true;
      this.contentOpacity = 1;
      const HeaderPlayer = document.getElementById(
        'video_video_header'
      ) as HTMLVideoElement;
      HeaderPlayer.src = 'https://image.91banban.com/ndswd18s_1206_x264.mp4';
      // HeaderPlayer.src = this.deployUrl + 'assets/video/head.mp4';
      HeaderPlayer.muted = true;
      HeaderPlayer.play();
      HeaderPlayer.onended = () => {
        HeaderPlayer.currentTime = 5;
        HeaderPlayer.play();
      };
    } else {
      this.mp4Hide = false;
      this.contentOpacity = 1;
      const player = document.getElementById(
        'video_video_front'
      ) as HTMLVideoElement;
      player.src = 'https://image.91banban.com/ndsdkc1206_x264.mp4';
      // player.src = this.deployUrl + 'assets/video/kaiping.mp4';
      player.muted = true;
      player.play();
      player.onended = () => {
        this.mp4Hide = true;
        this.contentOpacity = 1;
        const HeaderPlayer = document.getElementById(
          'video_video_header'
        ) as HTMLVideoElement;
        HeaderPlayer.src = 'https://image.91banban.com/ndswd18s_1206_x264.mp4';
        // HeaderPlayer.src = this.deployUrl + 'assets/video/head.mp4';
        HeaderPlayer.muted = true;
        HeaderPlayer.play();
        HeaderPlayer.onended = () => {
          HeaderPlayer.currentTime = 5;
          HeaderPlayer.play();
        };
      };
    }
    // 预热代码
    // this.startDate = 1668096000000; // 预热页面前端写死时间
    // this.TimeJudge();
    // this.roomPage = 'year';
    // 预热代码end
  }
  public getVisitActivity() {
    // 弹窗 登录任务
    this.yearawardService.visitActivityPage(
      (res) => {
        // console.log('访问活动页面=>', res);
        const num = res.data.num;
        // 今日未记录(num不为0) 弹窗 /* 获取数量 5/10 */
        if (num) {
          this.baseTask.desc += `${num}张`;
          this.task = this.baseTask;
          this.showTaskDialog = true;
        }
      },
      () => {}
    );
  }
  onSwiper([swiper]) {
    console.log(swiper);
  }
  onSlideChange(e) {
    console.log('slide change');
    console.log(e);
  }
  public onWindowScroll() {
    // 变量scrollTop是滚动条滚动时，距离顶部的距离
    const scrollTop =
      document.documentElement.scrollTop || document.body.scrollTop;
    if (scrollTop > 0) {
      this.flag = false;
    } else {
      this.flag = true;
    }
  }
  public closeShow(val) {
    const bodyEl = document.body;
    // let top = 0;
    if (val) {
      this.top = window.scrollY;
      bodyEl.style.position = 'fixed';
      bodyEl.style.top = -this.top + 'px';
    } else {
      bodyEl.style.position = '';
      bodyEl.style.top = '';
      window.scrollTo(0, this.top); // 回到原先的top
    }
    // const node = document.getElementById('content');
    // node.style.overflow = 'inherit';

    this.isRewardShow = val;
  }
  public closeReword(val) {
    const bodyEl = document.body;
    // let top = 0;
    if (val) {
      this.top = window.scrollY;
      bodyEl.style.position = 'fixed';
      bodyEl.style.top = -this.top + 'px';
      this.getUserInfo();
    } else {
      bodyEl.style.position = '';
      bodyEl.style.top = '';
      window.scrollTo(0, this.top); // 回到原先的top
    }
    this.isReword = val;
  }
  public getUserInfo() {
    this.yearawardService.userManualSignInDetails(
      (res) => {
        if (res.code === 200) {
          this.total = res.data.total;
          this.complete = res.data.complete;
        } else {
          this.baseservice.showToast(res.message, 1500);
        }
      },
      (err) => {}
    );
  }
  public goSignIn() {
    this.yearawardService.userManualSignInTask(
      (res) => {
        if (res.code === 200) {
          this.numh = res.data.num;
          this.isSign = true;
          this.getUserInfo();
        } else {
          this.baseservice.showToast(res.message, 1500);
        }
      },
      (err) => {}
    );
  }
  // 活动是否开始
  public TimeJudge() {
    const now = new Date().getTime();
    if (now < this.startDate) {
      this.activityStart = 'notstart'; // 活动未开始显示规则页
      this.countTime(); // 未开始显示倒计时
    } else {
      if (now < this.endDate) {
        this.activityStart = 'start'; // 活动进行中
      } else {
        this.activityStart = 'end'; // 活动结束
        this.roomPage = 'nvshen';
      }
    }
    this.yearawardService.setStartType(this.activityStart);
  }

  // 未开始-倒计时
  public countTime() {
    const date = new Date();
    const now = date.getTime();
    const differTime = this.startDate - now;
    if (differTime < 0) {
      setTimeout(() => {
        this.activityStart = 'start';
        window.location.reload();
      }, 1000);
      return;
    }
    let h: number;
    let m: number;
    let s: number;
    if (differTime >= 0) {
      h = Math.floor(differTime / 1000 / 60 / 60);
      m = Math.floor((differTime / 1000 / 60) % 60);
      s = Math.floor((differTime / 1000) % 60);
      if (h < 10) {
        this.hoursLeftNum = 0;
        this.hoursRightNum = h;
      } else {
        this.hoursLeftNum = Math.floor(h / 10);
        this.hoursRightNum = h % 10;
      }
      if (m < 10) {
        this.fenLeftNum = 0;
        this.fenRightNum = m;
      } else {
        this.fenLeftNum = Math.floor(m / 10);
        this.fenRightNum = m % 10;
      }
      if (s < 10) {
        this.miaoLeftNum = 0;
        this.miaoRightNum = s;
      } else {
        this.miaoLeftNum = Math.floor(s / 10);
        this.miaoRightNum = s % 10;
      }
      // 递归调用函数所以是延时器不是定时器
      setTimeout(() => {
        this.countTime();
      }, 1000);
    }
  }

  // 获取活动配置
  public getActivityTime() {
    return new Promise((r, j) => {
      this.yearawardService.getConfigs(
        (res: any) => {
          this.onRefrash = false;
          if (res.code === 200 && res.data[0]) {
            this.timeConfig = res.data;
            const nanEndList = this.timeConfig
              .filter((itm) => itm.type === 28)
              .sort(this.sortBy('startTime', undefined));
            this.defaultTabArray = [
              {
                tabImage:
                  this.deployUrl + 'assets/img/end-year/common/xinxiu.png',
                tabAcimage:
                  this.deployUrl + 'assets/img/end-year/common/xinxiuac.png',
                tabName: 'xinxiu',
                startTime: res.data.find((itm) => itm.type === 29).startTime,
                endTime: res.data.find((itm) => itm.type === 30).endTime,
                tips: '12月8日开启新秀'
              },
              {
                tabImage:
                  this.deployUrl + 'assets/img/end-year/common/renqi.png',
                tabAcimage:
                  this.deployUrl + 'assets/img/end-year/common/renqiac.png',
                tabName: 'renqi',
                startTime: res.data.find((itm) => itm.type === 21).startTime,
                endTime: res.data.find((itm) => itm.type === 21).endTime,
                tips: '12月8日开启人气'
              },
              {
                tabImage:
                  this.deployUrl + 'assets/img/end-year/common/nanshen.png',
                tabAcimage:
                  this.deployUrl + 'assets/img/end-year/common/nanshenac.png',
                tabName: 'nanshen',
                startTime: res.data.find((itm) => itm.type === 25).startTime,
                endTime: nanEndList[nanEndList.length - 1].endTime,
                tips: '12月10日开启男神'
              },
              {
                tabImage:
                  this.deployUrl + 'assets/img/end-year/common/nvshen.png',
                tabAcimage:
                  this.deployUrl + 'assets/img/end-year/common/nvshenac.png',
                tabName: 'nvshen',
                startTime: res.data.find((itm) => itm.type === 31).startTime,
                endTime: res.data.find((itm) => itm.type === 35).endTime,
                tips: '12月12日开启女神'
              },
              {
                tabImage:
                  this.deployUrl + 'assets/img/end-year/common/shenhao.png',
                tabAcimage:
                  this.deployUrl + 'assets/img/end-year/common/shenhaoac.png',
                tabName: 'shenhao',
                startTime: res.data.find((itm) => itm.type === 1).startTime,
                endTime: res.data.find((itm) => itm.type === 1).endTime,
                tips: '12月8日开启神豪'
              },
            ];
            this.startDate =
              res.data.find((itm) => itm.type === 1).startTime * 1000; // 活动开始时间 -- start
            this.endDate =
              res.data.find((itm) => itm.type === 1).endTime * 1000; // 活动结束时间--end
            this.yearawardService.setActivityDate(this.startDate);
            this.yearawardService.setEndDate(this.endDate);
            this.TimeJudge();
            r(res.data);
          }
        },
        (err) => {
          this.onRefrash = false;
        }
      );
    });
  }

  // 去刷新
  public refash() {
    this.onRefrash = true;
    setTimeout(() => {
      this.onRefrash = false;
    }, 500);
    this.getActivityTime().then((res) => {
      this.getVisitActivity();
      this.utilsservice.MsgSub.next();
    });
  }
  // 阻止冒泡
  public stopPropagation(e: any) {
    const e1 = e || window.event;
    e1.stopPropagation();
  }

  backApp() {
    if (this.isandroid) {
      // 安卓
      hideAndroidWebView();
    } else {
      hideIosWebView();
    }
  }
  // 按照num降序
  public sortBy(attr, rev) {
    if (rev === undefined) {
      rev = 1;
    } else {
      rev = rev ? 1 : -1;
    }

    return (a, b) => {
      a = a[attr];
      b = b[attr];
      if (a < b) {
        return rev * -1;
      }
      if (a > b) {
        return rev * 1;
      }
      return 0;
    };
  }
  // 跳转白名单直播间
  public getWhiteListroom() {
    this.yearawardService.getAnchorroom(
      (res) => {
        if (res.code === 200) {
          const obj = { ...res.data };
          obj.uid = res.data.anchorUid;
          obj.livimage = res.data.avatarUrl
            ? res.data.avatarUrl
            : 'https://image.91banban.com/moren_touxiang.png';
          obj.livImage = res.data.avatarUrl
            ? res.data.avatarUrl
            : 'https://image.91banban.com/moren_touxiang.png';
          this.utilsservice.gotoRoom({ ...obj }, 'anchor', []);
        } else {
          return this.baseservice.showToast(res.message, 1500);
        }
      },
      (err) => {}
    );
  }
  // tab切换
  public roomselectNav(tab) {
    if (this.roomPage === tab.tabName) {
      return;
    }
    const dates = new Date().getTime();
    if (dates < tab.startTime * 1000) {
      this.baseservice.showToast(tab.tips, 1500);
      return;
    }
    this.roomPage = tab.tabName;
    // this.currentTabArray.map((tab) => {
    //   tab.tabActive = false;
    // });
    // this.currentTabArray[index].tabActive = true;
    // this.roomPage = this.currentTabArray[index].tabName;
  }
  //跳转到福利
  public roomselectNavFili(name: string) {
    this.resetScroll();
    this.lastRoomPage = this.roomPage;
    this.roomPage = name;
  }
  //从福利返回活动
  public backToActivity() {
    this.roomPage = this.lastRoomPage;
  }
  /**
   * @description: "好的"
   */
  submitTaskDialog() {
    // this.showTaskDialog.next(false);
    this.showTaskDialog = false;
    console.log('=>', '..close');
  }

  resetScroll() {
    // 当前页面滚动置顶
    const wrapElement = this.wrap.nativeElement;
    wrapElement.scrollTo({ top: 0 });
  }
}
